package com.mx.project.controller;

import com.mx.project.common.resp.ApiResult;
import com.mx.project.common.util.JWTService;
import com.mx.project.constants.Constants;
import com.mx.project.pojo.Comment;
import com.mx.project.vo.CommentInfo;
import com.mx.project.services.CommentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Date;
import java.util.List;

@Log4j2
@Api(tags = "评论")
@RestController
@RequestMapping("comment")
public class CommentController {

    @Autowired
    private JWTService jwtService;

    @Autowired
    private CommentService commentService;

    @PostMapping()
    public ApiResult put(@RequestBody @Validated Comment comment, HttpServletRequest request){
        ApiResult apiResult = new ApiResult();
        Integer uid = jwtService.getUserId(request.getHeader("token"));
        comment.setUid(uid);
        comment.setCreateTime(new Date());
        int count = commentService.addComment(comment);
        return apiResult;
    }

    @ApiOperation("根据某个商品pid 来进行获取, 请求方式例如</br>  .../comment/1")
    @GetMapping("/{pid}")
    public ApiResult<List<CommentInfo>> get(@PathVariable("pid") Integer pid)  {
        ApiResult apiResult = new ApiResult();
        List<CommentInfo> list =commentService.getCommentByPid(pid);

        Path temp = Paths.get(Constants.AVATAR_FILE_PATH);
        if (!Files.isWritable(temp)) {
            try {
                Files.createDirectories(temp);
            } catch (IOException e) {
                log.error("创建文件夹失败!");
            }
        }
        for (int i = 0; i < list.size(); i++) {
            Path path = Paths.get(Constants.AVATAR_FILE_PATH + list.get(i).getAvatar());
            byte[] bytes = new byte[0];
            try {
                bytes = Files.readAllBytes(path);
                String avatar = Base64.getEncoder().encodeToString(bytes);
                list.get(i).setAvatar("data:image/"+list.get(i).getAvatar().substring(list.get(i).getAvatar().indexOf(".")+1)+";base64,"+avatar);
            } catch (IOException e) {
                log.error("获取图片失败!");
            }
        }
        apiResult.setData(list);
        return apiResult;
    }
    @ApiOperation("根据某个商品pid 来进行获取, 请求方式例如</br>  .../comment/1")
    @GetMapping("/test/{pid}")
    public ApiResult<List<CommentInfo>> get2(@PathVariable("pid") Integer pid){
        ApiResult apiResult = new ApiResult();
        List<CommentInfo> list =commentService.getCommentByPid(pid);
        apiResult.setData(list);
        return apiResult;
    }
}
